import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import App from './App.vue'
import routes from './router'

function getComponentPath(arr = [], comList) {

    arr.forEach(item => {
        if (item.children && item.children.length > 0) {
            getComponentPath(item.children, comList)
        } else {
            if (comList[`/src/${ item.component }`]) {
                console.log('匹配:', item.component)
                item.component = comList[`/src/${ item.component }`]
            }
        }
    })
    return arr
}


// 作为微应用被加载
if (window.__POWERED_BY_WUJIE__) {
    console.log('作为微应用被加载', import.meta.env.VITE_MICRO_TAG)
    let instance

    window.__WUJIE_MOUNT = () => {
        console.log('接收到主应用的props', window.$wujie.props)
        let remoteRoutes = window.$wujie?.props?.routers || []
        const components = import.meta.glob('@/views/**/*.vue')
        remoteRoutes = getComponentPath(remoteRoutes, components)
        // console.log('扫描', components)
        // console.log('平级后', remoteRoutes)
        const router = createRouter({
            // 	history: createWebHistory(window.__WUJIE_PUBLIC_PATH__ || '/'),
            history: createWebHistory(import.meta.env.VITE_MICRO_TAG),
            routes: remoteRoutes,
        })

        instance = createApp(App)
        const pinia = createPinia()

        for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
            instance.component(key, component)
        }

        instance.use(pinia)
        instance.use(router)
        instance.use(ElementPlus)
        instance.mount('#app')


        // 监听主应用发送的数据
        window.$wujie?.bus.$on('open-sub-change', function(arg) {
            console.log('监听主应用发送的数据', arg)
        })

        window.$wujie?.bus.$on('open-menu-change', function(routerName) {
            console.log('监听主应用点击菜单', routerName)
            router.push({ path: '/' + routerName })
        })
    }

    window.__WUJIE_UNMOUNT = () => {
        instance?.unmount()
    }
} else {
    // 独立运行
    console.log('独立运行', import.meta.env.VITE_MICRO_TAG)
    const app = createApp(App)
    const pinia = createPinia()
    const router = createRouter({
        history: createWebHistory(),
        routes: routes
    })

    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component)
    }

    app.use(pinia)
    app.use(router)
    app.use(ElementPlus)
    app.mount('#app')
}
